/*
 *  txdnet.cn tonydon
 * 
 */
package cn.txdnet.txcms.view.action;

import cn.txdnet.txcms.domain.TinyCmt;
import cn.txdnet.txcms.service.TinyCmtService;
import cn.txdnet.txweb.annotation.methods.GetMethod;
import cn.txdnet.txweb.annotation.methods.PostMethod;
import cn.txdnet.txweb.model.ModelUtil;
import cn.txdnet.txweb.model.ModelView;
import cn.txdnet.txweb.utils.BeanUtil;
import cn.txdnet.txweb.utils.Message;
import cn.txdnet.txweb.utils.RequestUtil;
import cn.txdnet.txweb.utils.SessionUtil;
import cn.txdnet.txweb.utils.WebUtil;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author txdnet
 */
public class TinyCmtAction {
    
    @GetMethod
    public ModelView index(HttpServletRequest req){
        long relateid = WebUtil.getLong(req, "relateid", -1);
        byte channeltype = WebUtil.getByte(req, "channeltype", -1);
        if(relateid<0 || channeltype<0){
            return ModelUtil.getTextModel(Message.MSG_PARAM_ERR);
        }
        Map p = new HashMap<String,Object>();
        p.put("relateid", relateid);
        p.put("channeltype", channeltype);
        return ModelUtil.getJspModel("post_form", p);
    }
    
    /**
     * 保存评论
     * @param req
     * @return
     * @throws Exception 
     */
    @PostMethod
    public ModelView save(HttpServletRequest req)throws Exception{
        String vcode = WebUtil.getNoNull(req, "vcode", null);
        String svcode = SessionUtil.getVcodeAndRemove(req);
        
        if(vcode==null || svcode==null || !svcode.equalsIgnoreCase(vcode)){
            return ModelUtil.getTextModel(Message.MSG_VCODE_ERR);
        }
        
        TinyCmt cmt = BeanUtil.parseRequestToBean(TinyCmt.class, req);
                cmt.setIp(RequestUtil.getRemoteAddr(req));
        if(!cmt.validate()){
            return ModelUtil.getTextModel(Message.MSG_FIELD_ERR);
        }
        if(TinyCmtService.make(cmt)){
            return ModelUtil.getTextModel(Message.MSG_SUCCESS);
        }else{
            return ModelUtil.getTextModel(Message.MSG_FAIL);
        }
    }
}
